package br.com.sca.interfaces;

import br.com.sca.dao.CarterinhaDAO;
import br.com.sca.dao.ConvenioDAO;
import br.com.sca.entidades.Aluno;
import br.com.sca.entidades.Carterinha;
import br.com.sca.entidades.Convenio;
import br.com.sca.entidades.Escola;
import br.com.sca.entidades.Login;
import br.com.sca.util.Constantes;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class CarterinhaFrame extends javax.swing.JInternalFrame {

    private DefaultTableModel tableModel;
    private ListSelectionModel listModel;
    private List<Carterinha> carterinhas;
    private int modo = 2;
    private Aluno aluno;
    private Escola escola;

    /**
     * Creates new form AlunoFrame
     */
    public CarterinhaFrame() {
        initComponents();
        defineModelo();
        desabilitaCampos();
        desabilitaBotoes();
        atualizaTabela();
    }

    private void defineModelo() {
        /**
         * Define os dados incluso na tabela
         */
        tableModel = (DefaultTableModel) tbCarterinha.getModel();

        /**
         * Escuta a tabela
         */
        listModel = tbCarterinha.getSelectionModel();
        listModel.addListSelectionListener(new ListSelectionListener() {

            /**
             * Executa quando um linha da tabela e executado
             *
             * @param e
             */
            @Override
            public void valueChanged(ListSelectionEvent e) {
                mostraDetalheConvenio();
            }
        });

        try {
            /*Cria a mascara para o CPF*/
            MaskFormatter cpfMafk = new MaskFormatter("###.###.###-##");
            cpfMafk.setValueContainsLiteralCharacters(false);
            DefaultFormatterFactory formatterCPF = new DefaultFormatterFactory(cpfMafk);
            //ftCpf.setFormatterFactory(formatterCPF);

            /*Cria a mascara para o Data Nascimento*/
            /*MaskFormatter nascMafk = new MaskFormatter("##/##/####");
             cpfMafk.setValueContainsLiteralCharacters(true);
             DefaultFormatterFactory formatterNasc = new DefaultFormatterFactory(nascMafk);
             ftNascimento.setFormatterFactory(formatterNasc);*/
        } catch (ParseException ex) {
            Logger.getLogger(CarterinhaFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Mosta o detalhe do aluno da linha selecionada
     */
    private void mostraDetalheConvenio() {
        if (tbCarterinha.getSelectedRow() != -1) {
            int linha = tbCarterinha.getSelectedRow();
            this.setAluno(carterinhas.get(linha).getAluno());
            this.setEscola(carterinhas.get(linha).getEscola());
            txAluno.setText(carterinhas.get(linha).getAluno().getNome());
            txEscola.setText(carterinhas.get(linha).getEscola().getEscola());
            ftDataEmissao.setValue(carterinhas.get(linha).getDataEmissao());
            ftDataVencimento.setValue(carterinhas.get(linha).getDataValidade());
        } else {
            limpaTela();
        }
    }

    /**
     * Atualiza a tabela com as inforamações da lista de Alunos
     */
    private void atualizaTabela() {
        CarterinhaDAO ld = new CarterinhaDAO();
        try {
            carterinhas = ld.listaCarterinhas();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar a lista de Carterinhas", "Erro", JOptionPane.ERROR_MESSAGE);
        }

        int numLinhas = tableModel.getRowCount();

        if (numLinhas > -1) {
            for (int i = 0; i < numLinhas; i++) {
                tableModel.removeRow(0);
            }

            for (int i = 0; i < carterinhas.size(); i++) {
                tableModel.insertRow(i, new Object[]{carterinhas.get(i).getId(), carterinhas.get(i).getAluno().getNome(), carterinhas.get(i).getEscola().getEscola(), carterinhas.get(i).getDataEmissao(), carterinhas.get(i).getDataValidade()});
            }
        }
    }

    private void desabilitaBotoes() {
        btBuscarAluno.setEnabled(false);
        btBuscarEscola.setEnabled(false);
        btSalvar.setEnabled(false);
        btSalvar.setEnabled(false);
        btCancelar.setEnabled(false);

        btNovo.setEnabled(true);
        btAlterar.setEnabled(true);
        btExcluir.setEnabled(true);

        btPesquisar.setEnabled(true);
    }

    private void habilitaBotoes() {
        btBuscarAluno.setEnabled(true);
        btBuscarEscola.setEnabled(true);
        btBuscarAluno.setEnabled(true);
        btSalvar.setEnabled(true);
        btCancelar.setEnabled(true);

        btNovo.setEnabled(false);
        btAlterar.setEnabled(false);
        btExcluir.setEnabled(false);

        btPesquisar.setEnabled(false);
    }

    /**
     * Habilita os campos para digitação
     */
    private void habilitaCampos() {

        txAluno.setEditable(false);
        txEscola.setEditable(false);
        ftDataEmissao.setEditable(true);
        ftDataVencimento.setEditable(true);
    }

    /**
     * Desabilita os campos pra digitação
     */
    private void desabilitaCampos() {

        txAluno.setEditable(false);
        txEscola.setEditable(false);
        ftDataEmissao.setEditable(false);
        ftDataVencimento.setEditable(false);
    }

    /**
     * Limpa os campos
     */
    private void limpaTela() {

        txAluno.setText("");
        txEscola.setText("");
        ftDataEmissao.setValue(null);
        ftDataVencimento.setValue(null);

    }

    private void adicionaConvenio() {
        if (aluno == null) {
            JOptionPane.showMessageDialog(this, "Campo aluno é obrigatorio", "Aviso", JOptionPane.WARNING_MESSAGE);
        } else {
            CarterinhaDAO ld = new CarterinhaDAO();
            Carterinha carterinha = new Carterinha();

            carterinha.setAluno(getAluno());
            carterinha.setEscola(getEscola());
            carterinha.setDataEmissao((Date) ftDataEmissao.getValue());
            carterinha.setDataValidade((Date) ftDataVencimento.getValue());
            try {
                ld.salvar(carterinha);
                atualizaTabela();
                desabilitaBotoes();
                desabilitaCampos();
                limpaTela();
                JOptionPane.showMessageDialog(this, "Carterinha registrado com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao tentar gravar o registro", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void alteraConvenio() {
        if (aluno == null) {
            JOptionPane.showMessageDialog(this, "Campo Aluno é obrigatorio", "Aviso", JOptionPane.WARNING_MESSAGE);
        } else {
            CarterinhaDAO ld = new CarterinhaDAO();
            Carterinha carterinha = new Carterinha();
            carterinha.setAluno(getAluno());
            carterinha.setEscola(getEscola());
            carterinha.setId(carterinhas.get(tbCarterinha.getSelectedRow()).getId());
            carterinha.setDataEmissao((Date) ftDataEmissao.getValue());
            carterinha.setDataValidade((Date) ftDataVencimento.getValue());
            try {
                ld.alterar(carterinha);
                atualizaTabela();
                desabilitaBotoes();
                desabilitaCampos();
                limpaTela();
                JOptionPane.showMessageDialog(this, "Carterinha alterado com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao tentar alterar o registro", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void excluirAluno() {
        if (tbCarterinha.getSelectedRow() != -1) {
            CarterinhaDAO ld = new CarterinhaDAO();
            Carterinha carterinha = new Carterinha();
            carterinha = carterinhas.get(tbCarterinha.getSelectedRow());
            ld.excluir(ld.carregar(carterinha.getId(), Carterinha.class));
            JOptionPane.showMessageDialog(this, "Carterinha excluido com sucesso!", "Informação", JOptionPane.INFORMATION_MESSAGE);
            limpaTela();
            desabilitaBotoes();
            desabilitaCampos();
            atualizaTabela();
        } else {
            JOptionPane.showMessageDialog(this, "Selecione um Carterinha para exclusão!", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnCabecalho = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        pnDados = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        ftDataEmissao = new javax.swing.JFormattedTextField();
        jLabel20 = new javax.swing.JLabel();
        txAluno = new javax.swing.JTextField();
        ftDataVencimento = new javax.swing.JFormattedTextField();
        btBuscarAluno = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txEscola = new javax.swing.JTextField();
        btBuscarEscola = new javax.swing.JButton();
        pnGrid = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbCarterinha = new javax.swing.JTable();
        jLabel19 = new javax.swing.JLabel();
        txPesquisa = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        pnButton = new javax.swing.JPanel();
        btNovo = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("SCA - Cadastro de Carterinhas");
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(650, 450));
        setRequestFocusEnabled(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pnCabecalho.setBackground(new java.awt.Color(0, 51, 255));

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cadastro de Carterinhas");
        pnCabecalho.add(jLabel1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(pnCabecalho, gridBagConstraints);

        pnDados.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        pnDados.setPreferredSize(new java.awt.Dimension(600, 100));

        jLabel6.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("Data Vencimento.:");

        jLabel7.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Data Emissão.:");

        ftDataEmissao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftDataEmissao.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        jLabel20.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Aluno.:");

        txAluno.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txAluno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txAlunoActionPerformed(evt);
            }
        });

        ftDataVencimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        ftDataVencimento.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        btBuscarAluno.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btBuscarAluno.setText("Buscar");
        btBuscarAluno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBuscarAlunoActionPerformed(evt);
            }
        });

        jLabel5.setText("Ex.(dd/mm/aaaa)");

        jLabel8.setText("ex.(dd/mm/aaaa)");

        jLabel9.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel9.setText("Escola.:");

        txEscola.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txEscola.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txEscolaActionPerformed(evt);
            }
        });

        btBuscarEscola.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btBuscarEscola.setText("Buscar");
        btBuscarEscola.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBuscarEscolaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnDadosLayout = new javax.swing.GroupLayout(pnDados);
        pnDados.setLayout(pnDadosLayout);
        pnDadosLayout.setHorizontalGroup(
            pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnDadosLayout.createSequentialGroup()
                        .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(pnDadosLayout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txEscola))
                            .addGroup(pnDadosLayout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ftDataEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ftDataVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8)
                            .addComponent(btBuscarEscola)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnDadosLayout.createSequentialGroup()
                        .addComponent(jLabel20)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txAluno, javax.swing.GroupLayout.PREFERRED_SIZE, 464, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btBuscarAluno)))
                .addContainerGap(157, Short.MAX_VALUE))
        );
        pnDadosLayout.setVerticalGroup(
            pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txAluno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btBuscarAluno))
                .addGap(2, 2, 2)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txEscola, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btBuscarEscola))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftDataEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftDataVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addGap(0, 15, Short.MAX_VALUE))
        );

        btBuscarAluno.getAccessibleContext().setAccessibleDescription("");

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 1;
        gridBagConstraints.ipady = 1;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(pnDados, gridBagConstraints);

        pnGrid.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.light"));
        pnGrid.setPreferredSize(new java.awt.Dimension(462, 200));
        pnGrid.setLayout(new java.awt.GridBagLayout());

        tbCarterinha.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        tbCarterinha.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Aluno", "Escola", "Dt. Emissão", "Dt. Validade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbCarterinha.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tbCarterinha);
        if (tbCarterinha.getColumnModel().getColumnCount() > 0) {
            tbCarterinha.getColumnModel().getColumn(0).setMaxWidth(50);
            tbCarterinha.getColumnModel().getColumn(1).setMaxWidth(310);
            tbCarterinha.getColumnModel().getColumn(2).setMaxWidth(310);
            tbCarterinha.getColumnModel().getColumn(3).setMaxWidth(100);
            tbCarterinha.getColumnModel().getColumn(4).setMaxWidth(100);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(jScrollPane1, gridBagConstraints);

        jLabel19.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel19.setForeground(new java.awt.Color(204, 0, 0));
        jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel19.setText("Pequisar por nome.:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(jLabel19, gridBagConstraints);

        txPesquisa.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        txPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txPesquisaActionPerformed(evt);
            }
        });
        txPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txPesquisaKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(txPesquisa, gridBagConstraints);

        btPesquisar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnGrid.add(btPesquisar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 1;
        gridBagConstraints.ipady = 1;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(pnGrid, gridBagConstraints);

        pnButton.setLayout(new java.awt.GridBagLayout());

        btNovo.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btNovo.setText("Novo");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btNovo, gridBagConstraints);

        btAlterar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btAlterar, gridBagConstraints);

        btExcluir.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btExcluir, gridBagConstraints);

        btCancelar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btCancelar, gridBagConstraints);

        btSalvar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnButton.add(btSalvar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(pnButton, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        if (modo == Constantes.INSERT_MODEL) {
            adicionaConvenio();
        } else if (modo == Constantes.EDIT_MODEL) {
            alteraConvenio();
            atualizaTabela();
            desabilitaBotoes();
            desabilitaCampos();
            limpaTela();
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void pesquisaUsuarioPorNome() {
        if (txPesquisa.getText().length() > 2) {
            CarterinhaDAO ld = new CarterinhaDAO();
            try {
                carterinhas = ld.pesquisarCarterinhaPorAluno(txPesquisa.getText());
                txPesquisa.setText("");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Erro ao carregar a lista de convênio", "Erro", JOptionPane.ERROR_MESSAGE);
            }

            int numLinhas = tableModel.getRowCount();
            for (int i = 0; i < numLinhas; i++) {
                tableModel.removeRow(0);
            }

            for (int i = 0; i < carterinhas.size(); i++) {
                tableModel.insertRow(i, new Object[]{carterinhas.get(i).getId(), carterinhas.get(i).getAluno().getNome(), carterinhas.get(i).getEscola().getEscola(), carterinhas.get(i).getDataEmissao(), carterinhas.get(i).getDataValidade()});
            }
        } else {
            JOptionPane.showMessageDialog(this, "Digite no mínimo 3 caracteres para realizar a pesquisa", "Informação", JOptionPane.INFORMATION_MESSAGE);
        }

    }

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        pesquisaUsuarioPorNome();
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        modo = Constantes.INSERT_MODEL;
        habilitaBotoes();
        habilitaCampos();
    }//GEN-LAST:event_btNovoActionPerformed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        if (tbCarterinha.getSelectedRow() != -1) {
            modo = Constantes.EDIT_MODEL;
            habilitaBotoes();
            habilitaCampos();
        } else {
            JOptionPane.showMessageDialog(null, "Selecione um aluno para alteração", "Atenção", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        desabilitaBotoes();
        desabilitaCampos();
        limpaTela();
        modo = 2;
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        excluirAluno();
    }//GEN-LAST:event_btExcluirActionPerformed

    private void txPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txPesquisaKeyReleased
        txPesquisa.setText(txPesquisa.getText().toUpperCase());
    }//GEN-LAST:event_txPesquisaKeyReleased

    private void txPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txPesquisaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txPesquisaActionPerformed

    private void btBuscarAlunoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBuscarAlunoActionPerformed
        AlunoFrame alunoFrame = new AlunoFrame(this);
        alunoFrame.setVisible(true);
        this.getDesktopPane().add(alunoFrame);
        alunoFrame.toFront();
    }//GEN-LAST:event_btBuscarAlunoActionPerformed

    private void btBuscarEscolaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBuscarEscolaActionPerformed
        EscolaFrame escolaFrame = new EscolaFrame(this);
        escolaFrame.setVisible(true);
        this.getDesktopPane().add(escolaFrame);
        escolaFrame.toFront();
    }//GEN-LAST:event_btBuscarEscolaActionPerformed

    private void txEscolaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txEscolaActionPerformed
        JOptionPane.showMessageDialog(this, "Click no botão Buscar para selecionar um Escola", "Aviso", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_txEscolaActionPerformed

    private void txAlunoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txAlunoActionPerformed
        JOptionPane.showMessageDialog(this, "Click no botão Buscar para selecionar um Aluno", "Aviso", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_txAlunoActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btBuscarAluno;
    private javax.swing.JButton btBuscarEscola;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btSalvar;
    private javax.swing.JFormattedTextField ftDataEmissao;
    private javax.swing.JFormattedTextField ftDataVencimento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnButton;
    private javax.swing.JPanel pnCabecalho;
    private javax.swing.JPanel pnDados;
    private javax.swing.JPanel pnGrid;
    private javax.swing.JTable tbCarterinha;
    private javax.swing.JTextField txAluno;
    private javax.swing.JTextField txEscola;
    private javax.swing.JTextField txPesquisa;
    // End of variables declaration//GEN-END:variables

    public Aluno getAluno() {
        return aluno;
    }

    public void setAluno(Aluno aluno) {
        this.aluno = aluno;
        txAluno.setText(aluno.getNome());
    }

    public Escola getEscola() {
        return escola;
    }

    public void setEscola(Escola escola) {
        this.escola = escola;
        txEscola.setText(escola.getEscola());
    }

}
